package com.buli.blmall.admin.core.security.provider;

import cn.hutool.crypto.digest.BCrypt;
import com.buli.blmall.admin.enums.LoginType;
import com.buli.blmall.admin.exception.LoginException;
import com.buli.blmall.admin.exception.error.LoginErrorCode;
import com.buli.blmall.admin.system.entity.SysUser;
import com.buli.blmall.admin.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * 密码认证
 * @author xiang.gao
 * @date 2025/3/3 15:54
 */
@Slf4j
@Component
public class PasswordAuthProvider extends BaseAuthProvider {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //用户名 密码
        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        SysUser sysUser = sysUserService.getByUsername(username);
        if (sysUser == null) {
            throw new LoginException(LoginErrorCode.USER_NOT_EXIST);
        }
        //校验密码
        checkLogin(LoginType.PASSWORD, username, () -> !BCrypt.checkpw(password, sysUser.getPassword()));
        //创建授权
        return createAuthentication(LoginType.PASSWORD, username, sysUser);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }

}
